package cn.xiehang.SoundSight;


import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FirstFragment extends Fragment {
    String GetShoppingUrl=SeverURL.URL+"/get_products";
    RecyclerViewAdapter2 adapter;
    RecyclerView recyclerView;
    CircularProgressIndicator progressIndicator;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        recyclerView = view.findViewById(R.id.first_fragment_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity())); // 或其他布局管理
        progressIndicator = view.findViewById(R.id.progressIndicator);

        //设置布局，使用StaggeredGridLayoutManager来实现瀑布流效果
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(
                1, // 列数（左右两列）
                StaggeredGridLayoutManager.VERTICAL // 垂直排列
        );

        recyclerView.setLayoutManager(layoutManager);
        // 创建数据，url方式调用
//        List<RecyclerViewItem> data = Arrays.asList(
//                new RecyclerViewItem("Item 1", Uri.parse("https://images.unsplash.com/photo-1506744038136-46273834b3fb")),
//                new RecyclerViewItem("Item 2", Uri.parse("https://images.unsplash.com/photo-1506744038136-46273834b3fb")),
//                new RecyclerViewItem("Item 3", Uri.parse("https://images.unsplash.com/photo-1506744038136-46273834b3fb"))
//        );


        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);

        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
        }
        else {
            progressIndicator.setVisibility(View.VISIBLE);
            getShoppingList();
        }


        return view;
    }
    public Boolean isLoggedIn() {
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        return sharedPref.getBoolean("is_logged_in", false);
    }
    public void onResume() {
        super.onResume();
        // 重新获取商品
        getShoppingList();
    }
    public static FirstFragment newInstance() {
        return new FirstFragment();
    }
    public void getShoppingList(){
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        String username= sharedPref.getString("username", null);
        String password= sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("username", username);
            jsonBody.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 构建 RequestBody
        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        // 创建请求
        Request request = new Request.Builder()
                .url(GetShoppingUrl)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("获取商品列表出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                String responseData = response.body().string();

                try {
                    // 解析JSON数据
                    JSONObject jsonObject = new JSONObject(responseData);
                    JSONArray productsArray = jsonObject.getJSONArray("products");

                    List<Product> productList = new ArrayList<>();

                    for (int i = 0; i < productsArray.length(); i++) {
                        JSONObject productJson = productsArray.getJSONObject(i);

                        int id = productJson.getInt("商品ID");
                        String name = productJson.getString("商品名称");
                        String description = productJson.getString("商品介绍");
                        double price = productJson.getDouble("商品价格");
                        String image = productJson.isNull("商品图片") ? null : productJson.getString("商品图片");
                        int quantity = productJson.getInt("商品数量");

                        Product product = new Product(id, name,  price, image, description,quantity);
                        productList.add(product);
                    }

                    // 回到UI线程更新界面
                    requireActivity().runOnUiThread(() -> {
                        // 这里你可以使用productList来更新UI
                        // 例如设置到RecyclerView适配器中
                        adapter = new RecyclerViewAdapter2(productList);
                        adapter.setOnItemClickListener(new RecyclerViewAdapter2.OnItemClickListener() {
                            @Override
                            public void onItemClick(Product product) {
                                FragmentActivity activity = getActivity();
                                if (activity != null) {
                                    // 执行 Fragment 切换
                                    FragmentManager fm = activity.getSupportFragmentManager();
                                    FragmentTransaction transaction = fm.beginTransaction();
                                    //隐藏所有的Fragment
                                    for (Fragment frag : fm.getFragments()) {
                                        if (frag != null && frag.isAdded()) {
                                            transaction.hide(frag);
                                        }
                                    }
                                    Fragment existingFragment = fm.findFragmentByTag("ShoppingFragment");

                                    if (existingFragment != null) {
                                        // 如果已经存在，则显示它
                                        //从存储信息获取对应商品信息

                                        Product Product1= getProduct(product);
                                        if (Product1!=null){
                                            product.setBuyCount(Product1.getBuyCount());
                                        }
                                        else {
                                            product.setBuyCount(0);
                                        }

                                        ((ShoppingFragment) existingFragment).setProduct(product);
                                        ((ShoppingFragment) existingFragment).setText();
                                        transaction.show(existingFragment);
                                    } else {
                                        Fragment shoppingCartFragment = new ShoppingFragment();
                                        Product Product1= getProduct(product);
                                        if (Product1!=null){
                                            product.setBuyCount(Product1.getBuyCount());
                                        }
                                        else {
                                            product.setBuyCount(0);
                                        }
                                        ((ShoppingFragment) shoppingCartFragment).setProduct(product);
                                        transaction.add(R.id.FragmentContainer, shoppingCartFragment, "ShoppingFragment");
                                    }
                                    transaction.commit();
                                }

                            }
                        });
                        recyclerView.setAdapter(adapter);
                        // 添加分割线
//        recyclerView.addItemDecoration(new DividerItemDecoration(this.getActivity(), DividerItemDecoration.VERTICAL));
                        // 设置默认动画
                        recyclerView.setItemAnimator(new DefaultItemAnimator());
                        progressIndicator.setVisibility(View.GONE);
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setTitle("解析数据出错")
                                .setMessage("error: " + e.getMessage())
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 关闭对话框
                                    dialog.dismiss();
                                })
                                .show();
                    });
                }
            }
        });

    }
    public Product getProduct(Product product){
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return null;
        }
        String username = sharedPref.getString("username", null);

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("cart"+username, Context.MODE_PRIVATE);

        String cartJson = sharedPreferences.getString("cart_items", "[]");
        Gson gson = new Gson();
        Type type = new TypeToken<List<Product>>() {}.getType();

        List<Product> cartItems = gson.fromJson(cartJson, type);

        for (Product item : cartItems) {
            if (item.getId() == product.getId()) {
                return item;
            }
        }
        return null;
    }
}

